package file

import (
	"cat-collage-backend/internal/config"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/qiniu/go-sdk/v7/storage"
	"gorm.io/gorm"
	"log"
)

func UploadFile(c *gin.Context, db *gorm.DB) {
	file, header, err := c.Request.FormFile("file")
	log.Println(file, "file")
	if err != nil {
		handleErr(c, err)
		return
	}
	defer func() {
		if file != nil {
			err = file.Close()
		}
		if err != nil {
			c.JSON(400, gin.H{"message": "上传文件失败"})
		}
	}()

	// 上传文件到七牛云
	uploaderCfg := storage.Config{}

	uploaderCfg.Zone = &config.Cfg.Upload.QiniuZone

	uploader := storage.NewFormUploader(&uploaderCfg)

	ret := storage.PutRet{}

	// 文件名
	fileName := header.Filename

	err = uploader.Put(context.Background(), &ret, config.Cfg.Upload.QiniuUpToken, fileName, file, header.Size, &storage.PutExtra{})

	handleErr(c, err)

}

func handleErr(c *gin.Context, e error) {
	if e != nil {
		c.JSON(400, gin.H{
			"message": "上传文件失败",
		})
		c.Abort()
		return
	}
}
